package com.college.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.college.eduservice.entity.EduSubject;
import com.college.eduservice.entity.ecxel.SubjectData;
import com.college.eduservice.service.EduSubjectService;
import com.college.servicebase.exceptionhandler.CollegeException;

/**
 * 因为SubjectExcelListener不能交给spring进行管理，需要自己手动new，
 * 也就不能注入其他对象，不能实现数据库操作
 * 解决办法：通过有参构造传EduSubjectService过来
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //读取excel内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new CollegeException(20001,"文件数据为空");
        }

        //一行一行读取，每次读取都要2个值(一级分类，二级分类)
        //判断一级分类是否重复
        EduSubject eduOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (eduOneSubject == null){ //没有一级分类，进行添加
            eduOneSubject = new EduSubject();
            eduOneSubject.setParentId("0");
            eduOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(eduOneSubject);
        }

        //获取一级分类id值
        String pid = eduOneSubject.getId();
        //判断二级分类是否重复
        EduSubject eduTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if (eduTwoSubject == null){ //没有二级分类，进行添加
            eduTwoSubject = new EduSubject();
            eduTwoSubject.setParentId(pid);
            eduTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(eduTwoSubject);
        }

    }

    //判读一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }
    //判读二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject two = subjectService.getOne(wrapper);
        return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
